package com.lxl.plugin.packagejar.ui;

import com.intellij.compiler.CompilerConfiguration;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;

import java.awt.*;
import java.util.*;

/**
 * Created by LXLong on 2015/2/13.
 */
public class Action extends AnAction {

    @Override
    public void update(AnActionEvent event) {
        super.update(event);
//        Presentation presentation = event.getPresentation();
//        System.out.println(presentation.isEnabled());
//        if(presentation.isEnabled()){
//            DataContext dataContext = e.getDataContext();
//            Project project = CommonDataKeys.PROJECT.getData(dataContext);
//            if(project==null){
//                presentation.setEnabled(false);
//                return;
//            }
//            Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext);
//            VirtualFile[] virtualFiles =a(project,CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext)) ;
//        }
//        VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
        Presentation presentation = event.getPresentation();
        if (presentation.isEnabled()) {
            DataContext dataContext = event.getDataContext();
//            presentation.setText(ActionsBundle.actionText("Compile"));
//            presentation.setVisible(true);
            Project project = CommonDataKeys.PROJECT.getData(dataContext);
            if (project == null) {
                presentation.setEnabled(false);
                presentation.setVisible(false);
                return;
            }
//            CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project);
//            Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext);
            VirtualFile[] virtualFiles = checkVirtualFiles(project, CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext));
            if (virtualFiles.length == 0) {
                presentation.setEnabled(false);
                presentation.setVisible(false);
                return;
            }
            String text;
            PsiPackage psiPackage = null;
            if (virtualFiles.length == 1) {
                PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(virtualFiles[0]);
                if (psiDirectory != null) {
                    psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
                }
            } else {
                PsiElement var12 = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
                if (var12 instanceof PsiPackage) {
                    psiPackage = (PsiPackage) var12;
                }
            }
            if (psiPackage != null) {
                text = psiPackage.getQualifiedName();
            } else if (virtualFiles.length == 1) {
                VirtualFile virtualFile = virtualFiles[0];
                //                    FileType fileType = virtualFile.getFileType();
                //                    if (!CompilerManager.getInstance(project).isCompilableFileType(fileType) && !compilerConfiguration.isCompilableResourceFile(project, virtualFile)) {
                //                        if (!ActionPlaces.isMainMenuOrActionSearch(event.getPlace())) {
                //                            presentation.setEnabled(false);
                //                            presentation.setVisible(false);
                //                            return;
                //                        }
                //                    } else {
                text = "'" + virtualFile.getName() + "'";
                //                    }
            } else {
                text = CompilerBundle.message("action.compile.description.selected.files", new Object[0]);
            }
            if (text == null) {
                presentation.setEnabled(false);
            } else {
                presentation.setText(getButtonName(text), true);
                presentation.setEnabled(true);
            }
        }
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        Setting setting = new Setting(event.getDataContext());
        setting.setResizable(false);
        setting.setSize(500, 200);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = setting.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        setting.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        setting.setTitle("Package Jars");
        setting.setVisible(true);
    }

//    public void test(AnActionEvent event) {
//        DataContext dataContext = event.getDataContext();
//        Project project = CommonDataKeys.PROJECT.getData(dataContext);
////        Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext);
//        Module module = LangDataKeys.MODULE.getData(dataContext);
////        if(module != null) {
////            System.out.println(">>>>>>>>>>>>>>3>>>>>>>>>>>>>>>>>");
////            CompilerManager.getInstance(project).compile(module, null);
////        } else{
////            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
////            VirtualFile[] virtualFiles = getVirtualFiles(project, CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext));
////            if(virtualFiles.length > 0) {
////                CompilerManager.getInstance(project).compile(virtualFiles, null);
////            }
////        }
//        Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
//
//        VirtualFile[] virtualFiles = checkVirtualFiles(project, CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext));
//
//        for(VirtualFile file : virtualFiles){
//            PsiDirectory directory = PsiManager.getInstance(project).findDirectory(file);
//            if(directory !=null){
//                System.out.println(Arrays.asList(directory.getSubdirectories()));
//                System.out.println(Arrays.asList(directory.getFiles()));
//            }else{
//
//            }
//        }
////        StringBuilder command = new StringBuilder();
////        command.append(sdk.getHomePath());
////        command.append("/bin/");
////        Process process;
////        try {
////            process = Runtime.getRuntime().exec(command.toString());
////            BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
////            String str;
////            while ((str = stream.readLine()) != null) {
////                System.out.println(str);
////            }
////        }catch (Exception e){
////            e.printStackTrace();
////        }
////        System.out.println(sdk.getName());
//    }

    public static void main(String[] args) {
//        String javac = "C:/Program Files (x86)/Java/jdk1.8.0_25/bin/jar cvf d:/jars/hello.jar -C d:/jars/ aa -C d:/jars/ cc";
//        Process process;
//        try {
//            process = Runtime.getRuntime().exec(javac);
//            BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            String str;
//            while ((str = stream.readLine()) != null) {
//                System.out.println(str);
//            }
//
////            process = Runtime.getRuntime().exec("javac");
////            stream = new BufferedReader(new InputStreamReader(process.getInputStream()));
////            while ((str = stream.readLine()) != null) {
////                System.out.println(str);
////            }
//        }catch (Exception e){
//            e.printStackTrace();
//
//        System.out.println(".jar.jar".matches("[^/\\\\<>*?|\"]+"));
    }

    private String getButtonName(String test) {
        StringBuilder sb = new StringBuilder(40);
        sb.append("Package Jars").append(" ");
        int length = test.length();
        if (length > 23) {
            if (StringUtil.startsWithChar(test, '\'')) {
                sb.append("\'");
            }
            sb.append("...");
            sb.append(test.substring(length - 20, length));
        } else {
            sb.append(test);
        }
        return sb.toString();
    }

    private VirtualFile[] checkVirtualFiles(Project project, VirtualFile[] virtualFiles) {
        if (virtualFiles != null && virtualFiles.length != 0) {
            PsiManager psiManager = PsiManager.getInstance(project);
            CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project);
            ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
            CompilerManager compilerManager = CompilerManager.getInstance(project);
            ArrayList arrayList = new ArrayList();
            VirtualFile[] _virtualFiles = virtualFiles;
            int length = virtualFiles.length;

            for (int i = 0; i < length; ++i) {
                VirtualFile virtualFile = _virtualFiles[i];
                if (projectFileIndex.isInSourceContent(virtualFile) && virtualFile.isInLocalFileSystem()) {
                    if (virtualFile.isDirectory()) {
                        PsiDirectory var11 = psiManager.findDirectory(virtualFile);
                        if (var11 == null || JavaDirectoryService.getInstance().getPackage(var11) == null) {
                            continue;
                        }
                        arrayList.add(virtualFile);
                    }
//                    else {
//                        FileType var12 = virtualFile.getFileType();
//                        if (!compilerManager.isCompilableFileType(var12) && !compilerConfiguration.isCompilableResourceFile(project, virtualFile)) {
//                            continue;
//                        }
//                    }
                }
            }
            return VfsUtilCore.toVirtualFileArray(arrayList);
        } else {
            return VirtualFile.EMPTY_ARRAY;
        }
    }

}
